package Servlet;

import POJO.User;
import DAO.*;
import POJO.Response;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import com.google.gson.Gson;

/**
 * 接口CheckUsername：检查用户名是否存在。
 */
public class CheckUsername extends HttpServlet{
    //TODO: 我感觉这种用静态可能会有问题
    class CheckUsernameData{
        private boolean isExisted;

        public CheckUsernameData(boolean isExisted) {
            this.isExisted = isExisted;
        }

        public boolean isExisted() {
            return isExisted;
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDAO userDao = new UserDAO();
        String username = req.getParameter("username");

        Response res;
        CheckUsernameData tempData;
        try{
            if(userDao.userNameExisted(username)){
                tempData = new CheckUsernameData(true);
            }else {
                tempData = new CheckUsernameData(false);
            }
            res = new Response(0,"查询成功",tempData);
        }catch(SQLException e){
            res = new Response(1001,"参数不正确",null);
        }


        resp.setContentType("text/json;charset=UtF-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        String json = gson.toJson(res);
        out.println(json);

    }
}
